<?php
namespace Modules\Payment\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Order\Entities\UnionOrder;
use \Modules\Order\Entities\BaseOrder as Order;

use Validator;
use ThrowException;
use Payment;
use Cache;
use Miniapp;

class PaymentCallbackController extends Controller
{
    // 微信支付回调
    public function wechatpayCallback(Request $req, $clientName, $paySubType)
    {
        $pay = Payment::wechatPay($clientName, $paySubType);

        try{
            $data = $pay->verify();

            $number = $data->out_trade_no;

            // 统一订单
            if ($number[0] === 'U') {
                $order = UnionOrder::getEntity([
                    'number' => $number
                ], false);
            }
            else {
                $order = Order::getDerivedOrder([
                    'pay_number' => $number
                ]);
            }

            if (!$order)
                return $pay->success();

            $options = [
                'pay_type' => 'wechat',
                'pay_sub_type' => $paySubType
            ];

            $order->completePay($options);

            $pay->recordPayment($order, $clientName, $paySubType, $data);

            // 小程序支付,则记录下prepay_id
            // if ($paySubType === 'miniapp') {
            //     $prepayId = Cache::get('prepay_id_' . $order->id);
            //     if ($prepayId)
            //         Miniapp::get($clientName)->setFormId($order->user, $prepayId, 'order');
            // }

            // Log::error($data);











        } catch (Exception $e) {
            // $e->getMessage();
        }
        
        return $pay->success();
    }

    // 头条系支付回调
    public function byteDancePayCallback(Request $req) 
    {
        $data = $req->all();
        \Log::error($data);

        // 检验回调数据的sign是否正确
        $pay = Payment::byteDancePay('default', 'wechat');
        $pay->checkCallbackData($data);

        $info = json_decode($data['msg'], true);
        $number = $info['cp_orderno'];

        // 统一订单
        if ($number[0] === 'U') {
            $order = UnionOrder::getEntity([
                'number' => $number
            ], false);
        }
        else {
            $order = Order::getDerivedOrder([
                'pay_number' => $number
            ]);
        }

        // 固定为微信
        $paySubType = 'wechat';
        $clientName = 'default';

        if (!$order)
            return $pay->success();

        $options = [
            'pay_type' => 'wechat',
            'pay_sub_type' => $paySubType
        ];

        $order->completePay($options);

        $pay->recordPayment($order, $clientName, $paySubType, $data);

        return $pay->success();
    }

}
